import React, { useEffect, useState, useImperativeHandle } from 'react';
import useForm from 'rc-form-hooks';
import { connect } from 'dva';
import { Form, Input, Button, Select, DatePicker } from 'antd';
import moment from 'moment'

import './index.styl';

const { Option } = Select;

function HeadForm({ dispatch, getFormData, dictionaryList: { caliList }, status, today, cRef }) {
  const { getFieldDecorator, resetFields, setFieldsValue, getFieldsValue, validateFields } = useForm();
  useImperativeHandle(cRef, () => ({
    getFieldsValue,
    resetFields
  }));
  useEffect(() => {
    if (status !== '') {
      resetFields()
      setFieldsValue({
        'status': status * 1,
      });
    }
    if (today !== '') {
      resetFields()
      setFieldsValue({
        'status': status * 1,
        'endTime': moment(Date.now()),      // 最近任务任务执行结束时间
        'startTime': moment(Date.now()),    // 最近任务任务执行开始时间
      });
    }
  }, [status, setFieldsValue, today, resetFields]);

  useEffect(() => {
    dispatch({
      type: 'dictionaryList/getCaliList',
    });
  }, [dispatch]);

  const handleSubmit = e => {
    e.preventDefault()
    validateFields()
      .then((values) => {
        const data = {
          ...values,
          startTime: values['startTime'] && values['startTime'].format('YYYY-MM-DD'),
          endTime: values['endTime'] && values['endTime'].format('YYYY-MM-DD'),
        }
        getFormData(data);
      })
      .catch(e => console.error(e.message))
  };

  // 开始时间
  const [startTime, setStartTime] = useState()

  // 结束时间
  const [endTime, setEndTime] = useState()

  // 重置
  const onReset = () => {
    setStartTime()
    setEndTime()
    resetFields()
    dispatch({
      type: 'deviceCali/updateSerachParams',
      payload: {
        serachParams: {
          current: 1
        }
      }
    });
  }

  // 开始时间
  const selectStartTime = (time, str) => {
    setStartTime(time)
  }

  // 开始时间
  const selectEndTime = (time, str) => {
    setEndTime(time)
  }

  // 设置开始不能选择的时间
  const disabledStartDate = startTime => {
    if (!startTime || !endTime) {
      return false
    }
    return startTime.valueOf() > endTime.valueOf()
  }

  //设置结束不能选择的时间
  const disabledEndDate = endTime => {
    if (!endTime || !startTime) {
      return false
    }
    return endTime.valueOf() <= startTime.valueOf()
  }

  return (
    <>
      <Form name="nest-messages" className="self-form" onSubmit={handleSubmit}>
        <div className="flex flex1">
          <Form.Item label="计划名称" colon={false}>
            {getFieldDecorator('name', {
              initialValue: '',
              rules: [{ required: false }],
            })(<Input className="self-input" placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="设备名称" colon={false}>
            {getFieldDecorator('deviceName', {
              initialValue: '',
              rules: [{ required: false }],
            })(<Input className="self-input" placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="设备使用部门" colon={false}>
            {getFieldDecorator('groupName', {
              initialValue: '',
              rules: [{ required: false }],
            })(<Input className="self-input" placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="检定员" colon={false}>
            {getFieldDecorator('assayUserName', {
              initialValue: '',
              rules: [{ required: false }],
            })(<Input className="self-input" placeholder="请输入" />)}
          </Form.Item>
        </div>
        <div className="flex">
          <Form.Item label="计划状态" colon={false}>
            {getFieldDecorator('status', {
              initialValue: '',
              rules: [{ required: false }],
            })(
              <Select placeholder="请选择" className="self-select" getPopupContainer={triggerNode => triggerNode.parentNode}>
                <Option value="">全部</Option>
                {caliList &&
                  caliList.planStatusList &&
                  caliList.planStatusList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>
                        {item.desc}
                      </Option>
                    );
                  })}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="执行状态" colon={false}>
            {getFieldDecorator('actionStatus', {
              rules: [{ required: false, message: '请选择' }],
            })(
              <Select placeholder="请选择" className="self-select" getPopupContainer={triggerNode => triggerNode.parentNode}>
                {caliList &&
                  caliList.runStatusList &&
                  caliList.runStatusList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>
                        {item.desc}
                      </Option>
                    );
                  })}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="执行时间" colon={false}>
            {getFieldDecorator('startTime', {
              rules: [{ required: false }],
            })(
              <DatePicker
                className="self-date"
                showToday={false}
                placeholder="选择开始时间"
                onChange={selectStartTime}
                disabledDate={disabledStartDate}
              />
            )}
          </Form.Item>
          <Form.Item label="">
            {getFieldDecorator('endTime', {
              rules: [{ required: false }],
            })(
              <DatePicker
                className="self-date"
                showToday={false}
                placeholder="选择结束时间"
                disabledDate={disabledEndDate}
                onChange={selectEndTime}
              />
            )}
          </Form.Item>
          <Button className="blue-button btn_styls" htmlType="submit">
            查询
          </Button>
          <Button className="white-button" htmlType="reset" onClick={() => onReset()}>
            重置
          </Button>
        </div>
      </Form>
    </>
  );
}

export default connect(({ deviceCali, dictionaryList }) => ({
  deviceCali,
  dictionaryList
}))(HeadForm);
